from django.shortcuts import render

# Create your views here.
from django.views import View
from .models import *
from rest_framework.views import APIView
from myapp import myserializers
from rest_framework.response import Response
from utils.captcha.captcha import captcha
from django.http import HttpResponse
import memcache

server = memcache.Client(["39.106.229.25:11211"])


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get("username")
        imagecode = request.data.get("imagecode")

        code = server.get(username)

        print(code)

        if imagecode.lower() != code.lower():
            return Response({'code': 500, 'data': '验证码错误'})

        user_ser = myserializers.UserSerializer(data=request.data)
        if user_ser.is_valid():
            user_ser.save()
            return Response({'code': 200, 'data': '创建成功'})
        else:
            return Response({'code': 500, 'data': '创建失败'})


class LoginView(APIView):
    def post(self, request):
        data = request.data
        print(data)
        user_ser = User.objects.filter(username=data['username'], password=data['password']).first()
        if user_ser:
            return Response({'code': 200, 'data': '登陆成功'})
        else:
            return Response({'code': 500, 'data': '登陆失败,账号不存在'})


class Imges(APIView):  # 验证码
    def get(self, request):
        name, text, image = captcha.generate_captcha()
        response = HttpResponse(image)
        response["Content-Type"] = "image/jpg"
        username = request.GET.get('username')
        server.set(username, text, 60)
        return response
